﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;

namespace EventLesson
{
    /// <summary>
    /// MouseEventWindow.xaml 的交互逻辑
    /// 在界面上移动鼠标，可以看到控件的位置随着鼠标移动而变化
    /// </summary>
    public partial class MouseEventWindow : Window
    {
        public MouseEventWindow()
        {
            InitializeComponent();
        }

        Point startPoint;
        bool isMoving = false;
        double left = 0;
        double top = 0;

        /// <summary>
        /// 鼠标左键按下事件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void Border_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            isMoving = true;
            startPoint = e.GetPosition(this.canvas);
            left = Canvas.GetLeft((UIElement)sender);
            top = Canvas.GetTop((UIElement)sender);

            Mouse.Capture((UIElement)sender);
        }

        private void Border_MouseMove(object sender, MouseEventArgs e)
        {
            if (!isMoving) return;
            Point p = e.GetPosition(this.canvas);
            double offsetX = p.X - startPoint.X;
            double offsetY = p.Y - startPoint.Y;
            Canvas.SetLeft((UIElement)sender, left + offsetX);
            Canvas.SetTop((UIElement)sender, top + offsetY);
        }

        private void Border_MouseLeftButtonUp(object sender, MouseButtonEventArgs e)
        {
            isMoving = false;
            Mouse.Capture(null);
        }

        private void canvas_MouseLeftButtonDown(object sender, MouseButtonEventArgs e)
        {
            Rectangle rect = new Rectangle();
            rect.Width = 100;
            rect.Height = 100;
            rect.Fill = Brushes.Red;
            rect.Stroke = Brushes.Black;
            rect.StrokeThickness = 2;
            rect.StrokeDashArray = new DoubleCollection(new double[] { 5, 5 });
            Canvas.SetLeft(rect, e.GetPosition(this.canvas).X - 50);
            Canvas.SetTop(rect, e.GetPosition(this.canvas).Y - 50);
            this.canvas.Children.Add(rect);
        }

        private void canvas_Click(object sender, RoutedEventArgs e)
        {

        }
    }
}
